<template>
  <div class="reportable">
    <h2>{{title}}{{showType=='time'?'分时':(showType=='distr'?'分布':'入店率')}}表</h2>
    <div class="export">
         <el-button @click="listdialog=true"  class="editbtn" size="medium" type="primary">表列修改</el-button>
    </div>
    <div class="export">
         <el-button v-show="true"
           @click="exportExcel"  :disabled="tableHead.length&&isShowExport?false:true" size="medium" type="primary">导出</el-button>
    </div>
    <div class="search-Box" >
      <el-input   placeholder="请输入关键字" class="table-search"  v-model="search">
        <i slot="prefix" class="el-input__icon el-icon-search"></i>
      </el-input>
    </div>
    <el-dialog
      title="表列修改"
      v-dialogDrag
      :close-on-click-modal='false' 
      :visible.sync="listdialog"
      @close="dialogClose"
      width="1000px"
      >
      <div class="coldiv">
        <el-checkbox-group v-model="colCheck" size="small">
          <el-checkbox v-for="item in colList" :key="item.key" :disabled="morenCol.includes(item.key)" :label="item.key" border>{{item.name}}</el-checkbox>
        </el-checkbox-group>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="listdialog = false">取 消</el-button>
        <el-button type="primary" @click="Colok()">确 定</el-button>
      </span>
    </el-dialog>
    <!--分时-->
    <el-table
      id="timetab"
      :data="tables"
      fit
      border
      :span-method="objectSpanMethod"
      :max-height="800"
      stripe
      v-if="showType=='time'"
      style="width:100%"
    >
      <el-table-column
        v-if="colCheckSave.includes('caseName')"
        class-name="tabfixed"
        :fixed="'left'"
        prop="case"
        label="案场名称"
        width="140"
        align="center"
      ></el-table-column>
      <el-table-column
          v-if="colCheckSave.includes('case_code')"
          class-name="tabfixed"
          :fixed="'left'"
          prop="case_code"
          label="案场编号"
          width="140"
          align="center"
      ></el-table-column>
      <el-table-column
        v-if="isType=='area'&&colCheckSave.includes('areaName')"
        class-name="tabfixed"
        :fixed="'left'"
        prop="area"
        label="区域名称"
        width="140"
        align="center"
      ></el-table-column>
      <el-table-column
        v-if="colCheckSave.includes('kpi')"
        class-name="tabfixed"
        :fixed="'left'"
        prop="kpi"
        label="指标"
        width="111"
        align="center"
      ></el-table-column>
      <el-table-column
        class-name="tabfixed"
        :fixed="'left'"
        prop="timeSlot"
        label="时间条件"
        width="120"
        align="center"
      ></el-table-column>
      <template v-for="item in tableHead.length>0?tableHead:defaultThead">
        <el-table-column
          :prop="item.prop"
          :label="item.label"
          :min-width="205"
          :key="item.prop"
          align="center"
        >
          <template slot-scope="scope" >
            <div v-if="(scope.row.max)== parseFloat(scope.row[item.prop])&&parseFloat(scope.row[item.prop])!=0" class="td-max-min">  
              <div class="maxdiv"> 
                <span class="td-max-span" >{{scope.row[item.prop]}}</span>
              </div>
            </div>
            <div v-else-if="(scope.row.min) == parseFloat(scope.row[item.prop])" class="td-max-min">
              <div class="mindiv"> 
                <span class="td-min-span">{{scope.row[item.prop]}}</span>
              </div>
            </div>
            <div v-else > 
              <div>
                <span>{{scope.row[item.prop]}}</span>
              </div>
            </div>
          </template>
        </el-table-column>
      </template>
      <el-table-column
        :fixed="'right'"
        prop="aver"
        label="平均"
        width="130"
        align="center"
      ></el-table-column>
      <el-table-column
        :fixed="'right'"
        prop="sum"
        label="小计"
        width="130"
        align="center"
      ></el-table-column>
    </el-table>
  </div>
</template>
<style lang="scss">
.reportable {
  width: 100%;
  background: #fff;
  padding: 32px;
  h2 {
    font-size: 17px;
    font-weight: 600;
    letter-spacing: 1px;
    margin-bottom: 18px;
    float: left;
  }
  .kpiBox{
    margin-right: 20px;
    float: right;
  }
  .el-table {
    color:#838ca1;
    .el-table__header-wrapper,
    .el-table__fixed,
    .el-table__fixed-right,
    .el-pagination,
    .el-table__fixed-header-wrapper {
      .has-gutter,
      thead {
        tr {
          th {
            background: #f5f6fa;
            color: #000a2c;
            font-weight: 400;
            line-height: 50px;
            padding-top: 0;
            padding-bottom: 0;
            .cell {
              white-space: pre-line !important;
            }
          }
        }
      }
    }
    .el-table__fixed-right-patch {
      border: none;
      background: #f5f6fa;
    }
    tbody {
      .td-max-min{
        display: inline-block;
        border-radius: 16px;
        overflow: hidden;
        height: 32px;
        vertical-align: middle;

        .maxdiv{
          position: relative;
          background: #F56C6C;
         // &::after{
          //   content: 'Max';
          //   background-color: #F56C6C;
          //   position: absolute;
          //   top: 0;
          //   right: 15px;
          //   transform: translateY(-50%) translateX(100%);
          //   border-radius: 10px;
          //   color: #FFF;
          //   display: inline-block;
          //   font-size: 12px;
          //   height: 18px;
          //   line-height: 18px;
          //   padding: 0 6px;
          //   text-align: center;
          //   white-space: nowrap;
          //   border: 1px solid #FFF;
         // }
        }
        .mindiv{
          position: relative;
          background: #67C23A;
          
         // &::after{
          //   content: 'Min';
          //   background-color: #67C23A;
          //   position: absolute;
          //   top: 0;
          //   right: 15px;
          //   transform: translateY(-50%) translateX(100%);
          //   border-radius: 10px;
          //   color: #FFF;
          //   display: inline-block;
          //   font-size: 12px;
          //   height: 18px;
          //   line-height: 18px;
          //   padding: 0 6px;
          //   text-align: center;
          //   white-space: nowrap;
          //   border: 1px solid #FFF;
         // }
        }
        .td-max-span{
          display: inline-block;
          height: 32px;
          line-height: 32px;
          padding: 0px 20px;
          font-size: 14px;
          color:#fff;          
        }
        .td-min-span{
          display: inline-block;
          height: 32px;
          line-height: 32px;
          padding: 0px 20px;
          font-size: 14px;
          color:#fff;
        }
      }

      .el-table__row {
        // &:hover {
        //   td {
        //      background: #f5f7fa;
        //   }
        // }
        td {
          line-height: 46px;
          height: 46px;
          /*div {*/
            /*line-height: 23px;*/
          /*}*/
          padding: 0;
        }
      }
      .el-table__row--striped {
        // &:hover {
        //   td {
        //      background: #e3efff;
        //   }
        // }
        td {
          background: #f4f9ff;
        }
      }
    }
    .el-table__body-wrapper {
      &::-webkit-scrollbar {
        width: 18px;
        height: 18px;
        //scrollbar-arrow-color: red;
      }

      /*定义滚动条轨道 内阴影+圆角*/
      &::-webkit-scrollbar-track {
        box-shadow: inset 0 0 5px rgba(0, 0, 0, 0.2);
        background: rgba(0, 0, 0, 0.1);
        border-radius: 10px;
      }

      /*定义滑块 内阴影+圆角*/
      &::-webkit-scrollbar-thumb {
        border-radius: 10px;
        box-shadow: inset 0 0 5px rgba(0, 0, 0, 0.2);
        background: rgba(0, 0, 0, 0.2);
        //scrollbar-arrow-color: red;
      }
    }
  }
  .el-pagination {
    text-align: right;
  }
  .search-Box{
    float: right;
      line-height: 30px;
        height: 30px;
        margin-bottom: 15px;
    .table-search{
      .el-input__inner{
            line-height: 30px;
        height: 30px;
      }
      .el-input__icon{
        line-height: 30px;
      }
    }
  }
  .export{
    float: right;
    height: 30px;
    line-height: 30px;
    margin-left: 5px;
    .el-button{
      padding: 0 15px;
      margin-top:1px;
      height: 30px;
      line-height: 30px;
      &.editbtn{
        border: 1px solid #cad7ff;
        background: #f2f5ff;
        color:#5f67ec;
        &:hover,&:focus{
          color: #FFFFFF;
          background-color: #545deb;
          border-color: #545deb;
        }
      }
    }

  }
  .coldiv{
    display: inline-block;
    .el-checkbox{
      text-align: center;
      width:120px;
      background: #f2f5ff;
      color: #5f67ec;
      border: 1px solid #cad7ff;
      margin: 0 20px 5px 0px !important;
      padding: 0 10px;
      line-height: 32px;
      top: -1px;
      position: relative;
       &.is-disabled{
        opacity: 0.3;
      }
    }
   
    .is-checked{
      background: #545deb;
      border: 1px solid #545deb;
      .el-checkbox__label{
        color: #fff;
      }
    }
    .el-checkbox__input{
      display: none;
    }
    .el-checkbox__label{
      display: inline;
      padding-left: 0px;
    }
  }
}
</style>
<script>
import FileSaver from 'file-saver';
import XLSX from 'xlsx';
import reportGlobal from "@/components/global/reportGlobal";//公共配置
let tableColCase = reportGlobal.tableColCase;
let tableColArea = reportGlobal.tableColArea;
export default {
  props: {
    isType:{
      default(){
        return 'area'            //是否是案场 不是为区域表格 默认不是
      }
    },
    tableData:{
      default(){
        return []
      }
    },
    tableHead:{
      default(){
        return []
      }
    },
    title:{
      default(){
        return ''
      }
    },
    isShowExport:false,
  },
  data() {
    return {
      spanArr: [], //合并行记录数组
      pos: [],
      spanArr2: [], //合并行记录数组
      pos2: [],
      showType:"time",
      search:'',
      defaultThead:[
        {label:'',prop:'1'},
        {label:'',prop:'2'},
        {label:'',prop:'3'},
      ],
      comData:{},         //头部条件
      comp_name:'',        //企业名

      listdialog:false,      //表列修改模态框
      colList:[],
      morenCol:['caseName','areaName','kpi','seatName'],
      colCheck:[],
      colCheckSave:[]
    };
  },
  components: {},
  created() {
    this.colList= this.isType=='case'?tableColCase:tableColArea;
    this.getCol();
  },
  computed:{
    tables: function () {
      let search = this.search;
      if (search) {
        return this.tableData.filter(function (dataNews) {
          return Object.keys(dataNews).some(function (key) {
            if(key.includes('id'))
            {
              return false; 
            }
            return String(dataNews[key]).toLowerCase().indexOf(search) > -1
          })
        })
      }
      return this.tableData
    }
  },
  mounted() {
    this.$Bus.$on('showTime',data=>{
      this.showType=data;
    });
    this.$Bus.$on('UpCondition',headVal=>{
        this.comp_name=headVal.comp_name;
    });
  },
  beforeDestroy(){
      this.$Bus.$off('showTime');
      this.$Bus.$off('UpCondition');
  },
  methods: {
 
    //表格合并行列。
    objectSpanMethod({ row, column, rowIndex, columnIndex }) {
      if(this.search){
        return {
          rowspan: 1,
          colspan: 1
        };
      }
      else{
        if (columnIndex === 0||columnIndex === 1) {
          const _row = this.spanArr[rowIndex];
          const _col = _row > 0 ? 1 : 0;
          return {
            rowspan: _row,
            colspan: _col
          };
        }else if(columnIndex === 2){
          const _row = this.spanArr2[rowIndex];
          const _col = _row > 0 ? 1 : 0;
          return {
            rowspan: _row,
            colspan: _col
          };
        }
      }

    },
    //导出表格
    exportExcel() {
      /* generate workbook object from table */
      let id = this.showType == 'time' ? '#timetab' : (this.showType == 'distr' ? '#distrtab' : 'xxx');
      let wb;
      let fix = document.querySelector('.el-table__fixed');
      if (fix) {
        wb = XLSX.utils.table_to_book(document.querySelector(id).removeChild(fix));
        document.querySelector(id).appendChild(fix);
      } else {
        wb = XLSX.utils.table_to_book(document.querySelector(id));
      }
      /* get binary string as output */
      let wbout = XLSX.write(wb, {bookType: 'xlsx', bookSST: true, type: 'array'});
      let name = this.comp_name + this.title + '分时表' ;

      try {
        FileSaver.saveAs(new Blob([wbout], {type: 'application/octet-stream'}), name + '.csv');
      } catch (e) {
        if (typeof console !== 'undefined')
          console.log(e, wbout)
      }
      return wbout
    },
    //表列选择确定
    Colok(){  
      let url='/sys/report_assist_new/set_web_custom_storage';
      let saveList=this.subSet(this.colCheck,this.morenCol);
      let parmas={
        w_key:this.isType,
        w_value:saveList.join(',')
      }
      this.$Bus.$emit("Loading", true);
      this.$api.post(url,parmas)
      .then(data=>{
        if(data.code==0){
          this.colCheckSave=this.colCheck;
          this.listdialog=false;
          this.$Bus.$emit("Loading", false);
          this.$message({
            showClose: true,
            message: '修改成功',
            type: 'success'
          });
        }
        else{
          this.$message({
            showClose: true,
            message: '修改失败',
            type: 'error'
          });
          this.$Bus.$emit("Loading", false);
        }
      })
      .catch(err=>{
         console.log(err);
        this.$Bus.$emit("Loading", false);
      })
    },
    //得到保存的表列
    getCol(){
      let url='/sys/report_assist_new/set_web_custom_storage?w_key='+this.isType;
      this.$api.get(url)
      .then(data=>{
        if(data.data)
        {
          let list=data.data.split(',');
          let arr=Array.from(new Set([...list,...this.morenCol]));
          this.colCheck=arr;
          this.colCheckSave=arr;
        }
        else{
          this.colCheck=this.morenCol;
          this.colCheckSave=this.morenCol;
        }
      })
      .catch(err=>{
         console.log(err);
      })
    },
    //取差集
    subSet(arr1,arr2){
      let set1 = new Set(arr1);
      let set2 = new Set(arr2);
      let subset = [];
      for (let item of set1) {
          if (!set2.has(item)) {
              subset.push(item);
          }
      }
      return subset;
    },
    //关闭模态框
    dialogClose(){
      this.colCheck=this.colCheckSave;
    },
    //根据内容相同合并那几行
    getSpanArr() {
      let data = this.tableData;
      this.spanArr = [];
      this.spanArr2 = [];
      this.pos = 0;
      this.pos2 = 0;
      for (var i = 0; i < data.length; i++) {
        if (i === 0) {
          this.spanArr.push(1);
          this.spanArr2.push(1);
          this.pos = 0;
          this.pos2 = 0;
        } else {
          // 判断当前元素与上一个元素是否相同
          if (data[i].case_id === data[i - 1].case_id&&data[i].case_code!='变化值'&&data[i-1].case_code!='变化值') {
            this.spanArr[this.pos] += 1;
            this.spanArr.push(0);
          } else {
            this.spanArr.push(1);
            this.pos = i;
          }
          if (data[i].area_id === data[i - 1].area_id &&this.isType=='area'&&data[i].case_code!='变化值'&&data[i-1].case_code!='变化值') {
            this.spanArr2[this.pos2] += 1;
            this.spanArr2.push(0);
          } else {
            this.spanArr2.push(1);
            this.pos2 = i;
          }
        }
      }
      this.$Bus.$emit("Loading", false);

    },
  },
  watch: {
    tableData: {
      //深度监听，可监听到对象、数组的变化
      handler(newV, oldV) {
        //do something, 可使用this
        this.$Bus.$emit("Loading", false);
        this.getSpanArr();
      },
      deep: true
    },
  }
};
</script>
